package com.micro.glszh.stat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.micro.glszh.stat.config.Const;
import com.micro.glszh.stat.dao.SysUserMapper;
import com.micro.glszh.stat.domain.SysUser;
import com.micro.glszh.stat.domain.dto.UserInfo;
import com.micro.glszh.stat.domain.vo.UserPassVo;
import com.micro.glszh.stat.exception.BadRequestException;
import com.micro.glszh.stat.service.SysUserService;
import com.micro.glszh.stat.utils.JwtToken;
import com.micro.glszh.stat.utils.PageResult;
import com.micro.glszh.stat.utils.PageUtil;
import com.micro.glszh.stat.utils.RsaUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;

/**
 * SysUserServiceImpl
 *
 * @Author gaopengfei
 * @create 2024/10/21 15:53
 */
@RequiredArgsConstructor
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    private final SysUserMapper userMapper;
    @Override
    public Boolean updatePass(UserPassVo passVo) {
        // 密码解密
        try {
            String oldPass = RsaUtils.decryptByPrivateKey(Const.PRIVATE_KEY, passVo.getOldPass());
            SysUser user = this.getById(1);
            String password = RsaUtils.decryptByPrivateKey(Const.PRIVATE_KEY, user.getPassword());
            if (!password.equals(oldPass)) {
                throw new BadRequestException("原始密码不正确！");
            }
            user.setPassword(passVo.getNewPass());
            return this.saveOrUpdate(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Map<String, Object> login(String phone, String password) {
        SysUser user = this.getOne(new QueryWrapper<SysUser>().lambda().eq(SysUser::getPhone, phone));
        if (Objects.isNull(user)) {
            throw new BadRequestException("用户不存在，请先联系管理员注册！");
        }
        try {
            String input = RsaUtils.decryptByPrivateKey(Const.PRIVATE_KEY, password);
            String userPassword = RsaUtils.decryptByPrivateKey(Const.PRIVATE_KEY, user.getPassword());
            if (!userPassword.equals(input)) {
                throw new BadRequestException("密码不正确！");
            }
        } catch (Exception e) {
            throw new BadRequestException("请求失败！");
        }
        String token = JwtToken.makeToken(Long.valueOf(user.getId()), user.getDataSource());
        String expiresTimeStr = JwtToken.getExpireTime(token);
        // 返回 token
        Map<String, Object> map = new LinkedHashMap<>(2);
        UserInfo userInfo = new UserInfo();
        BeanUtil.copyProperties(user, userInfo);
        map.put("token", token);
        map.put("expires_time", expiresTimeStr);
        map.put("userInfo", userInfo);
        return map;
    }

    @Override
    public PageResult<SysUser> list(Integer page, Integer size, String name, String phone) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .like(StrUtil.isNotBlank(name), SysUser::getName, name)
                .or()
                .like(StrUtil.isNotBlank(phone), SysUser::getPhone, phone);
        Page<SysUser> sysUserPage = userMapper.selectPage(new Page<>(page, size), wrapper);
        return PageUtil.toPage(sysUserPage);
    }

    @Override
    public Boolean resetPassword(Integer id) {
        // 密码解密
        try {
            String newPass = RsaUtils.encryptByPublicKey(Const.PUBLIC_KEY, "123456");
            SysUser user = this.getById(id);
            user.setPassword(newPass);
            return this.saveOrUpdate(user);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
